from uuid import uuid1
from cgi import parse_qs
from google.appengine.api import memcache

def home(environ, start_response):
    indexFile = open ('index.html', 'r')  
    response_body = indexFile.read()


    status = '200 OK'
    response_headers = [('Content-Type', 'text/html'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)
    return [response_body]

def login(environ, start_response):
    params = parse_qs(environ['QUERY_STRING'])
    nickName = params.get('name', [''])[0]
    response_body = str(uuid1())

    status = '200 OK'
    response_headers = [('Content-Type', 'text/html'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)
    return [response_body]

def send(environ, start_response):
    params = parse_qs(environ['QUERY_STRING'])
    clientId = params.get('clientId', [''])[0]
    msg = params.get('msg', [''])[0]
    response_body = 'success';


    clientMsgs = memcache.get('clientMsgs')
    if clientMsgs is None:
         clientMsgs = {}
         
    
    if clientId not in clientMsgs:
        clientMsgs[clientId] = []

    msgs = clientMsgs[clientId]
    msgs.append(msg)
    memcache.set('clientMsgs', clientMsgs)


    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)
    return [response_body]

def read(environ, start_response):
    params = parse_qs(environ['QUERY_STRING'])
    clientId = params.get('clientId', [''])[0]

    response_body = ''
    clientMsgs = memcache.get('clientMsgs')
    if clientMsgs is not None:
        if clientId in clientMsgs:
            msgs = clientMsgs[clientId]
            response_body = str(msgs)

    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)
    return [response_body]